require("../util.js");
require("../component/components.js");
require("../../jsMt/util.js");
var userInfo=JSON.parse(sessionStorage.getItem("userInfo"));
var shopData=JSON.parse(sessionStorage.getItem("shopData"));
var freightData=JSON.parse(sessionStorage.getItem("freightData"+userInfo.chatId));
if(!userInfo){
    location.href="/loginIndex"
}
var vm = new Vue({
    el:"#addGoods",
    data:{
        isScreen:"",
        shopData:shopData,
        freightData:freightData,
        shopCategorys:[],
        initId1:"",
        initId1Name:"",
        rCategorys:[],
        initId2:"",
        initId2Name:"",
        rCategorys1:[],
        initId3:"",
        initId3Name:"",
        number:1,
        formatNum:1,
        freightName:"包邮",
        // addressId:"",
        // addressList:{},
        infoName:"",
        isGoodsInfo:false,  //是否显示图文详情
        list:{
            loginUid:userInfo.id,
            title:"", //商品名称
            imgSrc:[],  //商品图片
            mediaCategoryId:"", //分类id
            userFreightId :"0", //运费模板
            content:"", //商品内容
            model:[],  //商品型号数组
            price:[],  //商品价格数组
            num:[], //数量数组
            skuId:[] //sku数组
        },
        type:"",   //1 编辑 2添加
        name:"",
        productId:"",
        imgSrc:[],
        productIdInfo:{},
        numberA:"",
        imgSrcList:[],
        circleId:""
    },
    mounted:function(){
        this.searchObject = this.getQueryStringArgs();
        if(this.searchObject&&this.searchObject.userFreightId){
            this.list.userFreightId=this.searchObject&&this.searchObject.userFreightId;
            this.freightName=decodeURI(this.searchObject&&this.searchObject.freightName);
        }
        // this.data.loginUid=this.searchObject&&this.searchObject.uid;
        this.type=this.searchObject&&this.searchObject.type;
        if(this.type==1){
            this.productId=this.searchObject&&this.searchObject.productId;
            this.name="编辑商品";
            this.getMediaProductById();
        }else if(this.type==2){
            this.numberA=this.searchObject&&this.searchObject.number;
            this.circleId=this.searchObject&&this.searchObject.circleId;
            this.name="添加商品";
        }else if(this.type==3){
            this.name="添加商品";
        }
        // // this.square=this.searchObject&&this.searchObject.square;
        //this.getChinaList();
    },
    methods:{
        //后退
        getBack: function () {
            sessionStorage.removeItem("freightData"+userInfo.chatId);
            if(this.type==2){
                location.href="/myGoods?type=2&uid="+this.list.loginUid+"&number="+this.numberA+"&circleId="+this.circleId;
            }else if(this.type==3){
                history.go(-1);
                //location.href="/myGoods?type=3&uid="+this.list.loginUid+"&number="+this.numberA;
            }else{
                location.href="/happyi/myCommodity";
            }
            // history.go(-1);
        },
        bgimg:function(url){
            url = url?url:"";
            return {
                "background-image":'url("'+url+'"),url("")'
            }
        },
        /*获取查询字符对象*/
        getQueryStringArgs: function () {
            //取得查询字符串并去掉开头的问号
            var qs = (location.search.length > 0 ? location.search.substring(1) : ""),
                args = {},
                items = qs.length ? qs.split("&") : [],
                item = null,
                name = null,
                value = null,
                len = items.length;
            for (var i = 0; i < len; i++) {
                item = items[i].split("=");
                name = item[0];
                value = item[1];
                if (name.length) {
                    args[name] = value;
                }
            }
            return args;
        },
        //个人商品详情
        getMediaProductById:function(){
            var that=this;
            var data={
                loginUid:that.list.loginUid,
                productId:that.productId
            };
            this.ajax({url:"/happyi/getMediaProductById",data:data,dataType:"json",method:"post"},function(b){
                if(b.json.code==0&&b.json.data){
                    that.productIdInfo=b.json.data;
                    that.list.title=that.productIdInfo.title;
                    that.list.mediaCategoryId=that.productIdInfo.categoryId;
                    that.initId3Name=that.productIdInfo.categoryName;
                    that.list.content=that.productIdInfo.descript;
                    if(that.productIdInfo.descript){
                        that.infoName="已添加";
                    }

                    if(that.freightData&&that.freightData.userFreightId==0){

                    }else if(that.freightData&&that.freightData.userFreightId){

                    }else{
                        that.list.userFreightId=that.productIdInfo.freightId;
                        that.freightName=that.productIdInfo.freightName;
                    }

                    // that.freightName=that.productIdInfo.freightName;
                    // that.list.imgSrc=that.productIdInfo.images;
                    if(that.productIdInfo.images&&that.productIdInfo.images.length>0){
                        that.number=that.productIdInfo.images&&that.productIdInfo.images.length;
                    }
                    that.productIdInfo.skus&&that.productIdInfo.skus.forEach(function(val,index){
                        // that.list.model.splice(index,0,val.model);
                        that.list.model.push(val.model);
                        that.list.price.push(val.price);
                        that.list.num.push(val.num);
                        that.list.skuId.push(val.skuId);
                    });
                    that.formatNum=that.productIdInfo.skus&&that.productIdInfo.skus.length;
                }else{
                    vm.$refs.prompt.toast("获取个人商品详情失败！");
                }
            });
        },
        //删除商品图片
        deleteProductByImgId:function(index,imgId){
            var that=this;
            if(imgId){
                var data={
                    loginUid:that.list.loginUid,
                    imgId:imgId
                };
                console.log(data)
                this.ajax({url:"/happyi/deleteProductByImgId",data:data,dataType:"json",method:"post"},function(b){
                    if(b.json.code==0){
                        that.getMediaProductById();
                        vm.$refs.prompt.toast("操作成功！");
                    }else{
                        vm.$refs.prompt.toast("删除图片失败！");
                    }
                });
            }else{
                that.getClose(index)
            }

        },
        getIsScreen:function(num){
            console.log(num)
            this.isScreen=num;
            if(num==1){
                this.shopCategorys=[];
                this.rCategorys=[];
                this.rCategorys1=[];
                this.initId1="";
                this.initId1Name="";
                this.initId2="";
                this.initId2Name="";
                this.recruitCategorys(0,0)
            }
        },
        recruitCategorys:function(id,type,name){
            var that=this;
            if(type==1){
                that.rCategorys=[];
                that.rCategorys1=[];
                that.initId1=id;
                that.initId1Name=name;
            }else if(type==2){
                that.rCategorys1=[];
                that.initId2=id;
                that.initId2Name=name;
            }
            that.shopData.allMediaShopCategorys.forEach(function(item,index){
                if(item.parentId==id){
                    if(type==0){
                        that.shopCategorys.push(item)
                    }else if(type==1){
                        that.rCategorys.push(item);
                    }else if(type==2){
                        that.rCategorys1.push(item);
                    }
                }
            });
            console.log(that.rCategorys);
        },
        getClass:function(item){
            this.list.mediaCategoryId=item.mediaCategoryId;
            this.initId3Name=item.name;
            this.getIsScreen();
        },
        //图片
        getChange:function(index){
            var that=this;
            console.log("33333333333增加"+index)
            var fileinput=document.getElementById("fileinput"+index).files[0];
            fileinput = new File([fileinput], new Date().getTime()+".png",{type:"image/jpeg"});
            var coverBtn=document.getElementById("coverBtn"+index).className;
            if(coverBtn=="coverImg-show"){
                that.list.imgSrc.splice(index,1,fileinput);
            }else{
                if(that.type==1){
                    that.list.imgSrc.splice(index,0,{"imgSrc":fileinput});
                }else{
                    that.list.imgSrc.splice(index,0,fileinput);
                }
            }
            console.log(that.list.imgSrc)
            lrz(fileinput, function (results) {
                // 你需要的数据都在这里，可以以字符串的形式传送base64给服务端转存为图片。
                // that.results=results;
                console.log(results)
                if(coverBtn=="coverImg-show"){
                    that.imgSrcList.splice(index,1,results.base64);
                }else{
                    if(that.type==1){
                        that.imgSrcList.splice(index,0,{"imgSrc":results.base64});
                    }else{
                        that.imgSrcList.splice(index,0,results.base64);
                    }
                }
                that.number++;
                document.getElementById("coverImg"+index).src=results.base64;
                if(index==0){
                    document.getElementById("coverlable"+index).className="coverImg-show";
                }
                document.getElementById("coverBtn"+index).className="coverImg-show";
            });
        },
        //删除图片
        getClose:function(index){
            var that=this;
            that.list.imgSrc.splice(index,1);
            document.getElementById("coverImg"+index).src="";
            if(index==0){
                document.getElementById("coverlable"+index).className="";
            }
            document.getElementById("coverBtn"+index).className="";
            that.number--;
            //console.log(that.list.imgSrc)
        },
        getNext:function(type){
            if(type==1){
                console.log(type)
                this.isGoodsInfo=!this.isGoodsInfo;
                console.log(this.isGoodsInfo)
                //location.href="/addGoodsInfo"
            }else if(type==2){
                var data=this.list,path;
                data.categoryName=this.initId3Name;
                data.imgSrcList=this.imgSrcList;
                console.log(data.imgSrc)
                sessionStorage.setItem("freightData"+userInfo.chatId,JSON.stringify(data));
                if(freightData&&freightData.userFreightId){
                    path="/freightTemplate?userFreightId="+freightData.userFreightId+"&type="+this.type;
                }else{
                    path="/freightTemplate?userFreightId="+this.list.userFreightId+"&type="+this.type;
                }
                //path="/freightTemplate?userFreightId="+this.list.userFreightId+"&type="+this.type;
                if(this.type==1&&this.productId){
                    path+="&productId="+this.productId;
                }
                location.href=path;
                // if(this.list.userFreightId){
                //     location.href="/freightTemplate?userFreightId="+this.list.userFreightId;
                // }else{
                //     location.href="/freightTemplate";
                // }

            }
        },
        //保存图文详情
        createGroup:function(){
            var content =$('#content').getValue();
            this.list.content=content;
            this.infoName="已添加";
            this.getNext(1);
        },
        //添加商品规格
        getAddBtn:function(type,index){
            var that=this;
            console.log("ddd");
            if(type==1){
                that.formatNum++;
                if(that.type==1){
                    that.list.skuId.push("");
                }
            }else if(type==2){
                that.list.model.splice(index,1);
                that.list.price.splice(index,1);
                that.list.num.splice(index,1);
                if(that.type==1){
                    that.list.skuId.splice(index,1);
                }
                that.formatNum--;

            }
        },
        //删除Sku
        deleteSku:function(index,skuId){
            var that=this;
            if(skuId){
                var data={
                    loginUid:that.list.loginUid,
                    skuId:skuId
                };
                console.log(data)
                this.ajax({url:"/happyi/deleteSku",data:data,dataType:"json",method:"post"},function(b){
                    if(b.json.code==0){
                        //that.getMediaProductById();
                        that.getAddBtn(2,index)
                        //vm.$refs.prompt.toast("操作成功！");
                    }else{
                        vm.$refs.prompt.toast("删除规格失败！");
                    }
                });
            }else{
                that.getAddBtn(2,index)
            }
        },
        //删除商品
        deleteProduct:function(){
            var that=this;
            var data={
                loginUid:that.list.loginUid,
                productId:that.productId
            };
            console.log(data)
            this.ajax({url:"/happyi/deleteProduct",data:data,dataType:"json",method:"post"},function(b){
                if(b.json.code==0){
                    that.getBack();
                    //that.getMediaProductById();
                    //that.getAddBtn(2,index)
                    //vm.$refs.prompt.toast("操作成功！");
                }else{
                    vm.$refs.prompt.toast("删除规格失败！");
                }
            });
        },
        //添加商品
        saveProduct:function(){
            var that=this;
            console.log(that.list)
            if(that.list.title&&that.list.loginUid&&that.list.mediaCategoryId&&that.list.userFreightId&&that.list.content&&that.list.model&&that.list.price&&that.list.num){

            }else{
                vm.$refs.prompt.toast("请完善商品信息！");
                return false;
            }
            var imgSrcList=that.list.imgSrc;
            // if(imgSrcList.length>0){}
            var formData = new FormData();
            var modelList=that.list.model;
            for(var i=0;i<modelList.length;i++){
                formData.append("model",modelList[i]);
            }
            var priceList=that.list.price;
            for(var i=0;i<priceList.length;i++){
                formData.append("price",priceList[i]);
            }
            var numList=that.list.num;
            for(var i=0;i<numList.length;i++){
                formData.append("num",numList[i]);
            }
            formData.append("title", that.list.title);
            formData.append("loginUid", that.list.loginUid);
            formData.append("mediaCategoryId",that.list.mediaCategoryId);
            formData.append("userFreightId", that.list.userFreightId);
            formData.append("content", that.list.content);
            // formData.append("imgSrc", that.list.imgSrc);
            // formData.append("model", that.list.model);
            // formData.append("price",that.list.price);
            // formData.append("num",that.list.num);
            // if(!that.data.circleName){
            //     vm.$refs.prompt.toast("圈子名称不能为空！");
            //     return;
            // }
            var url;
            if(that.type==1){
                console.log(imgSrcList.length)
                var skuIdList=that.list.skuId;
                console.log(skuIdList.length)
                for(var i=0;i<skuIdList.length;i++){
                    formData.append("skuId",skuIdList[i]);
                }
                formData.append("productId", that.productId);
                if(imgSrcList.length>0){
                    for(var i=0;i<imgSrcList.length;i++){
                        formData.append("imgSrc",imgSrcList[i].imgSrc);
                    }
                    url=host+"/v1/mediaShop/updateProductByImg";   //https://api.hongkzh.cn/
                }else{
                    var data={
                        loginUid:that.list.loginUid,
                        productId:that.productId,
                        title:encodeURI(that.list.title), //商品名称
                        mediaCategoryId:that.list.mediaCategoryId, //分类id
                        userFreightId :that.list.userFreightId, //运费模板
                        content:encodeURI(that.list.content) //商品内容
                        // model:that.list.model,  //商品型号数组
                        // price:that.list.price,  //商品价格数组
                        // num:that.list.num, //数量数组
                        // skuId:that.list.skuId//sku数组
                    };//=that.list;
                    var categorys;
                    var models=[];
                    for(var i=0;i<modelList.length;i++){
                        // console.log(modelList[i])
                        categorys={};
                        categorys.model=modelList[i];
                        models.push($.param(categorys));
                    }
                    data.model=models.join("&");

                    var prices=[];
                    for(var i=0;i<priceList.length;i++){
                        // console.log(modelList[i])
                        categorys={};
                        categorys.price=priceList[i];
                        prices.push($.param(categorys));
                    }
                    data.price=prices.join("&");

                    var nums=[];
                    for(var i=0;i<numList.length;i++){
                        // console.log(modelList[i])
                        categorys={};
                        categorys.num=numList[i];
                        nums.push($.param(categorys));
                    }
                    data.num=nums.join("&");

                    var skuIds=[];
                    for(var i=0;i<skuIdList.length;i++){
                        // console.log(modelList[i])
                        categorys={};
                        categorys.skuId=skuIdList[i];
                        skuIds.push($.param(categorys));
                    }
                    data.skuId=skuIds.join("&");
                    that.updateProduct(data);
                    return false;

                    //url="http://192.168.100.104:8083/v1/mediaShop/updateProduct";
                }
            }else if(that.type==2||that.type==3){
                for(var i=0;i<imgSrcList.length;i++){
                    formData.append("imgSrc",imgSrcList[i]);
                }
                url=host+"/v1/mediaShop/saveProduct";
            }
            console.log(formData)
            $.ajax({
                url:url,
                type:'POST',
                data:formData,
                dataType:'json',
                async: false,
                cache: false,
                contentType: false, //不设置内容类型
                processData: false, //不处理数据
                traditional:true,
                success:function(data){
                    console.log(data);
                    // alert(data.msg);
                    if(data.code==0){
                        that.getBack();
                        //location.href="/friend?indexs=3"
                    }
                },
                error:function(){
                    vm.$refs.prompt.toast("添加商品失败！")
                }
            });
        },
        //修改商品不带图片的
        updateProduct:function(data){
            var that=this;
            console.log(data)
            this.ajax({url:"/happyi/updateProduct",data:data,dataType:"json",method:"post"},function(b){
                if(b.json.code==0){
                    that.getBack();
                    // vm.$refs.prompt.toast("操作成功！");
                }else{
                    vm.$refs.prompt.toast("删除图片失败！");
                }
            });

        }
    },
    watch: {
        rCategorys:function(){
            this.$nextTick(function(){
                var that=this;
                var container = document.querySelectorAll('#screen .chooseCity-city')[0];

                var expansion = null; //是否存在展开的list
                    var x, y, X, Y, swipeX, swipeY;
                    container.addEventListener('touchstart', function(event) {
                       // console.log(container)
                        x = event.changedTouches[0].pageX;
                        y = event.changedTouches[0].pageY;
                        swipeX = true;
                        swipeY = true ;
                        // if(expansion){   //判断是否展开，如果展开则收起
                        //     expansion.className ="chooseCity-city clearfix";
                        // }
                        //event.stopPropagation();
                    });
                    container.addEventListener('touchmove', function(event){
                        event.stopPropagation();
                        X = event.changedTouches[0].pageX;
                        Y = event.changedTouches[0].pageY;
                        // 左右滑动
                        if(swipeX && Math.abs(X - x) - Math.abs(Y - y) > 0){
                            // 阻止事件冒泡
                            event.stopPropagation();
                            if(X - x > 10){   //右滑
                                // event.preventDefault();
                                this.className = "chooseCity-city clearfix";    //右滑收起
                            }
                            if(x - X > 10){   //左滑
                                event.preventDefault();
                                this.className = "chooseCity-city clearfix swipeleft";   //左滑展开
                                // expansion = this;
                            }
                            swipeY = false;
                        }
                        // 上下滑动
                        if(swipeY && Math.abs(X - x) - Math.abs(Y - y) < 0) {
                            swipeX = false;
                        }
                    });
            });
        }
        ,list:{
            handler:function(val, oldVal) {
               console.log(val)
                if(val.model&&val.num&&val.price){
                    for(var i=0;i<val.num.length;i++){
                        val.num[i]=Math.abs(val.num[i]);
                        val.price[i]=Math.abs(val.price[i]);
                    }
                }
            },
            deep: true
        },
        type:function(){
            var that=this;
            if(that.type!=1&&freightData){
                console.log(freightData)
                that.list.title=freightData.title;
                that.list.mediaCategoryId=freightData.mediaCategoryId;
                that.initId3Name=freightData.categoryName;
                that.list.content=freightData.content;
                if(freightData.content){
                    that.infoName="已添加";
                }
                // that.list.imgSrc=freightData.imgSrc;
                // if(freightData.imgSrcList&&freightData.imgSrcList.length>0){
                //     that.number=freightData.imgSrcList.length;
                //     that.productIdInfo.images=freightData.imgSrcList;
                // }
                console.log(that.productIdInfo.images);
                if(freightData.model&&freightData.model.length>0){
                    that.formatNum=freightData.model&&freightData.model.length;
                }
                that.list.model=freightData.model;
                that.list.price=freightData.price;
                that.list.num=freightData.num;

            }
        }
    }
});
$('#content').artEditor({
    imgTar: '#imageUpload',
    limitSize: 5,   // 兆
    showServer: true,
    uploadUrl: host+"/v1/mediaShop/saveProductDetailImg",
    data: {loginUid:vm.list.loginUid},
    uploadField: 'image',
    breaks: false,
    placeholader: '请输入...',
    validHtml: ["<br/>"],
    formInputId: 'target',
    uploadSuccess: function (res) {
        console.log(res)
        // 这里是处理返回数据业务逻辑的地方
        // `res`为服务器返回`status==200`的`response`
        // 如果这里`return <path>`将会以`<img src='path'>`的形式插入到页面
        // 如果发现`res`不符合业务逻辑
        // 比如后台告诉你这张图片不对劲
        // 麻烦返回 `false`
        // 当然如果`showServer==false`
        // 无所谓咯
        // return res;
    },
    uploadError: function (status, error) {
        //这里做上传失败的操作
        //也就是http返回码非200的时候
        alert('网络异常' + status)
    }
});